// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'

// 全局配置ElementUI
Vue.use(ElementUI)

import { getApiBaseURL } from './config/apiConfig'

// 配置axios
// 使用配置文件动态获取baseURL，支持代理和直连两种模式
axios.defaults.baseURL = getApiBaseURL()
axios.defaults.timeout = 30000
axios.defaults.withCredentials = false
// 确保请求和响应的字符编码正确
axios.defaults.headers.common['Accept'] = 'application/json, text/plain, */*'
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.responseType = 'text'
axios.defaults.responseEncoding = 'utf8'

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('请求错误:', error)
    if (error.response) {
      switch (error.response.status) {
        case 404:
          ElementUI.Message.error('请求的资源不存在')
          break
        case 500:
          ElementUI.Message.error('服务器内部错误')
          break
        default:
          ElementUI.Message.error('请求失败：' + error.message)
      }
    } else {
      ElementUI.Message.error('网络连接错误')
    }
    return Promise.reject(error)
  }
)

// 将axios添加到Vue原型，方便在组件中使用
Vue.prototype.$http = axios

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
